var express = require('express')
var router = express.Router()
const multer  = require('multer')

// 方法1:
// const upload = multer({ dest: 'public/uploads/' }) //指定文件存放路径
// router.post('/upload',upload.single('picture'),(req,res)=>{
//   console.log(req.file);
// })

// 方法2:
const storage = multer.diskStorage({
  destination: function (req, file, cb) { //指定存放路径
    cb(null, 'public/uploads/')
  },
  filename: function (req, file, cb) { //指定存放的文件名
    // console.log(req.files,file);
    const name = Math.random().toString(36).substring(2)+Date.now() //生成随机字符串
    let type = file.mimetype.split('/')[1] //图片后缀
    cb(null, `${name}.${type}`)
  }
})
const upload = multer({ storage: storage })
router.post('/upload',upload.single('picture'),(req,res)=>{
  // console.log(req.file);
  res.send({
    code:1,
    msg:'上传成功',
    data:{
      url:`/uploads/${req.file.filename}`
    }
  })
})

module.exports = router